package com.saishi.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.stream.JsonReader;
import com.saishi.dao.BookDao;
import com.saishi.dao.BooksQuestionDao;
import com.saishi.dao.QuestionDao;
import com.saishi.dao.impl.BookDaoImpl;
import com.saishi.dao.impl.BooksQuestionDaoImpl;
import com.saishi.dao.impl.QuestionDaoImpl;
import com.saishi.entity.Book;
import com.saishi.entity.Question;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "DatabankServlet", value = "/user/question/databank/*")
public class DatabankServlet extends BaseOneServlet {
    BookDao bookDao = new BookDaoImpl();
    QuestionDao questionDao = new QuestionDaoImpl();
    BooksQuestionDao booksQuestionDao = new BooksQuestionDaoImpl();

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String sbookid = request.getParameter("bookid");
        String squestionid = request.getParameter("questionid");
        String smybookid = request.getParameter("mybookid");
        int mybookid = 0;
        if (smybookid != null && !"".equals(smybookid))
            mybookid = Integer.parseInt(smybookid);

        Gson gson = new Gson();
        JsonArray jsonArray = gson.fromJson(squestionid, JsonArray.class);
        Object[][] del = new Object[jsonArray.size()][2];
        JsonArray jsonBook = gson.fromJson(sbookid, JsonArray.class);
        Object[][] add = new Object[jsonBook.size() * jsonArray.size()][2];
        for (int i = 0; i < jsonArray.size(); i++) {
            int questionid = Integer.parseInt(jsonArray.get(i).getAsString());
            del[i][0] = questionid;
            del[i][1] = mybookid;
        }
        int index = 0;
        for (int i = 0; i < jsonBook.size(); i++) {
            int bookid = Integer.parseInt(jsonBook.get(i).getAsString());
            for (int j = 0; j < jsonArray.size(); j++) {
                int questionid = Integer.parseInt(jsonArray.get(j).getAsString());
                add[index][0] = questionid;
                add[index][1] = bookid;
                index++;
            }
        }
        int[] ints = booksQuestionDao.deleteOne(del);
        int[] insert = booksQuestionDao.insert(add);
//        System.out.println(Arrays.toString(ints) + "\n" + Arrays.toString(insert));
        response.sendRedirect("/user/question/");
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String bookname = request.getParameter("bookname");

        int insert = 0;
        Book book = null;
        book = new Book();
        book.setBookname(bookname);
        try {
            insert = bookDao.insert(book);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        response.sendRedirect("/user/question/");
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String[] questionid = request.getParameterValues("questionid");
        String bookid = request.getParameter("bookid");
        String[] split = questionid[0].split(",");
//        System.out.println(Arrays.toString(questionid) + ":" + bookid + ":" + Arrays.toString(split));
        Object[][] obj = new Object[split.length][];
        for (int i = 0; i < split.length; i++) {
            obj[i] = new Object[1];
            obj[i][0] = split[i];
        }
        int[] delete = new int[0];
        if (!questionid[0].equals("")) {
            try {
                delete = questionDao.delete(obj);
                booksQuestionDao.delete(obj);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        response.sendRedirect("/user/question/databank?bookid=" + bookid + "");
//        PrintWriter out = response.getWriter();
//        out.println("<script src=\"/javascript/jquery-1.8.2.min.js\"></script><script>$(function(){$.extend({StandardPost:function(url,args){var form = $(\"<form method='post'></form>\"),input;$(document.body).append(form);form.attr({\"action\":url});$.each(args,function(key,value){input = $(\"<input type='hidden'>\");input.attr({\"name\":key});input.val(value);form.append(input)});console.log(args);form.submit()}});" +
//                "$.StandardPost('/user/question/databank/',{bookid:" + bookid + "});});</script>");
//        String json = "{ \"bookid\" : \"" + bookid + "\", \"delState\" : \"" + Arrays.toString(delete) + "\"}";
//        out.println(json);
//        out.flush();
//        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sbookid = request.getParameter("bookid");
        String spage = request.getParameter("page");
//        System.out.println(sbookid + ":" + spage);
        int page = 1;
        if (spage != null && !("".equals(spage)))
            page = Integer.parseInt(spage);
        int bookid = 1;
        if (sbookid != null && !"".equals(sbookid))
            bookid = Integer.parseInt(sbookid);
        List<Question> questions = null;
        Book query = null;
        List<Book> books = null;
        List<Object> book = null;
        List lists = new ArrayList();
        Long count = 0L;
        try {
            questions = questionDao.bookQuery(bookid, (page - 1) * 10, 10);
            query = bookDao.query(bookid);
            books = bookDao.allQuery();
            count = booksQuestionDao.count(bookid);
            for (Book b : books) {
                book = new ArrayList<Object>();
                book.add(b.getBookid());
                book.add(b.getBookname());
                book.add(b.getBookdesc());
                book.add(booksQuestionDao.count(b.getBookid()));
                lists.add(book);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        Gson gson = new Gson();
        List questionoptions = new ArrayList();
        Map map = null;
        for (Question q : questions) {
            if (q.getQuestiontype() != 2) {
                map = new HashMap();
                String s = q.getQuestionoptions();
                JsonReader jsonReader = new JsonReader(new StringReader(s));
                jsonReader.setLenient(true);
                jsonReader.beginObject();
                while (jsonReader.hasNext()) {
                    String key = jsonReader.nextName();
                    String val = jsonReader.nextString();
                    if (val == "")
                        continue;
                    map.put(key, val);
//                if (key.equals("A")) {
//                    map.put(key,val);
//                } else if (key.equals("B")) {
//                    map.put(key,val);
//                } else if (key.equals("C")) {
//                    map.put(key,val);
//                } else if (key.equals("D")) {
//                    map.put(key,val);
//                } else if (key.equals("E")) {
//                    map.put(key,val);
//                } else if (key.equals("F")) {
//                    map.put(key,val);
//                } else {
//                    System.err.println(key + ":" + val);
//                }
//                System.out.println(key + ":" + val);
                }
                jsonReader.endObject();
                questionoptions.add(map);
            }
        }
        request.setAttribute("questions", questions);
        request.setAttribute("book", query);
        request.setAttribute("books", lists);
        request.setAttribute("page", page);
        request.setAttribute("count", Math.ceil((double) count / 10));
        request.setAttribute("questionoptions", questionoptions);
        request.getRequestDispatcher("/WEB-INF/user/databank.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
